package cn.itlight.basic.utils;

import cn.itlight.basic.jwt.*;
import cn.itlight.user.domain.Logininfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.security.PublicKey;

//登录上下文，把登录的相关信息放到这里面，方便调用
// 问题1：
/**
* @Description: 登录上下文工具类，获取当前登录人信息
* @Author: Mr.She
* @Version: 1.0
* @Date:  2022/7/3 11:20
*/
@Slf4j
public class LoginContext {

    /**
     * @Title: getLogininfo
     * @Description: 获取到登录用户的logininfo
     * @Author: Mr.She
     * @Version: 1.0
     * @Date:  2022/7/16 9:27
     * @Parameters: []
     * @Return cn.itsource.user.domain.Logininfo
     */
    public static Logininfo getLogininfo(HttpServletRequest req) {
        try {
            // 1.从请求头中获取token，判断是否存在
            String token = req.getHeader("token");
            // 1.解析token得到载荷数据
            PublicKey publicKey = RsaUtils.getPublicKey(JwtRasHolder.INSTANCE.getJwtRsaPubData());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            // 2.判断载荷数据不为空时，说明已经是登录成功了，那么就不拦截
            if (payload == null){
                log.error("getLogininfo error...");
                return null;
            }
            return payload.getUserInfo().getLogininfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}